<template>
  <div class="workstage_tab table_panel table_container tab_pane">
    <el-table
      class="table_dialog"
      :data="workStageListFilter"
      height="440"
      border
      style="width: 100%"
      tooltip-effect="dark"
      :row-class-name="isFinished">
      <mes-col-comp :key="index + 'A'" v-for="(column, index) in workstageTableColums.partA" :column="column"></mes-col-comp>
      <el-table-column
        prop="planStartDate"
        label="工序计划开始时间"
        align="center"
        width="160">
        <template slot-scope="scope">
          <div class="plane_startTime">
            <el-date-picker
              :disabled="isDisabled(scope.row)"
              :clearable="false"
              v-model="scope.row.planStartDate"
              align="right"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd 00:00:00"
              :picker-options="getPickerOptionsStart(scope.row.planEndDate)">
            </el-date-picker>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="planEndDate"
        label="工序计划完成时间"
        align="center"
        width="160">
        <template slot-scope="scope">
          <div class="plane_endTime">
            <el-date-picker
              :disabled="isDisabled(scope.row)"
              :clearable="false"
              v-model="scope.row.planEndDate"
              align="right"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd 23:59:59"
              :picker-options="getPickerOptionsEnd(scope.row.planStartDate)">
            </el-date-picker>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :class-name="'table_select'"
        label="执行班组"
        prop="workgroupId"
        width="200">
        <template slot-scope="scope">
          <el-select
            :disabled="isDisabled(scope.row)"
            filterable
            placeholder="请选择"
            v-model="scope.row.workgroupId"
            class="type_list"
            :class="saveHandler&&!scope.row.workgroupId ? 'error_input':''"
            @change="workgroupChange(scope.row)">
            <el-option
              v-for="item in scope.row.nametree"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        :class-name="'table_select'"
        prop="workcenterId"
        label="工作中心"
        width="200">
        <template slot-scope="scope">
          <el-select
            :disabled="isDisabled(scope.row)"
            filterable
            placeholder="请选择"
            v-model="scope.row.workcenterId"
            class="type_list"
            popper-class="disabled_select"
            :class="saveHandler&&!scope.row.workcenterId ? 'error_input':''"
            @change="workcenterChange(scope.row)">
            <el-option
              v-for="item in scope.row.workCenterList"
              :disabled="item.useFlag === '0'"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        :class-name="'table_select'"
        prop="deviceIds"
        label="设备"
        width="200">
        <template slot-scope="scope">
          <el-select
            v-if="multipleStatus"
            :disabled="isDisabled(scope.row)"
            filterable
            multiple
            collapse-tags
            :multiple-limit="100"
            placeholder="请选择"
            v-model="scope.row.deviceIds"
            popper-class="disabled_select"
            class="type_list"
            @remove-tag="removeTagSelect(scope.row, 'device')">
            <el-option
              v-for="item in scope.row.deviceList"
              :disabled="item.useFlag === '0'"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        :class-name="'table_select'"
        prop="staffIds"
        label="人员"
        width="200">
        <template slot-scope="scope">
          <el-select
            v-if="multipleStatus"
            :disabled="isDisabled(scope.row)"
            filterable
            multiple
            collapse-tags
            :multiple-limit="100"
            placeholder="请选择"
            v-model="scope.row.staffIds"
            popper-class="disabled_select"
            class="type_list"
            @remove-tag="removeTagSelect(scope.row, 'staff')">
            <el-option
              v-for="item in scope.row.staffList"
              :disabled="item.useFlag === '0'"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <mes-col-comp :key="index + 'B'" v-for="(column, index) in workstageTableColums.partB" :column="column"></mes-col-comp>
    </el-table>
  </div>
</template>

<script>
import workstageTableColums from './workstageTableColums'
export default {
  name: 'WorkstageTab',
  props: {
    workStageList: {
      type: Array,
      defaultProps: []
    },
    multipleStatus: {
      type: Boolean,
      defaultProps: false
    },
    saveHandler: {
      type: Boolean,
      defaultProps: false
    },
    planEndDate: ''
  },
  data() {
    return {
      workstageTableColums: workstageTableColums
    }
  },
  computed: {
    // 工序进度状态
    workstageProcessStatus() {
      return this.$store.state.dict.workstageProcessStatusType.labels || []
    },
    // 当前0点0分0秒时间戳
    todayMillisecond() {
      return this.moment(window.serverTime).startOf('day').unix() * 1000
    },
    // 表格数据--需给每一行数据初始化添加：workCenterList、deviceList、staffList属性
    workStageListFilter() {
      return this.workStageList.map(obj => {
        let item = JSON.parse(JSON.stringify(obj))
        if (item.workgroupId) {
          item.workCenterList = this.parseData(item.nametree, item.workgroupId, 'workcenter', [item.workcenterId])
        }
        if (item.workcenterId) {
          item.deviceList = this.parseData(item.workCenterList, item.workcenterId, 'device', item.deviceIds)
          item.staffList = this.parseData(item.workCenterList, item.workcenterId, 'staff', item.staffIds)
        }
        return item
      }) || []
    }
  },
  methods: {
    /**
     * 解析树形子集，如选择工厂时获取所选工厂下的车间列表
     * @param {Array} list 父集列表
     * @param {String} id 所选父集元素id
     * @param {Array} field 表示子集的字段名称，如：workshops（车间）
     * @returns {Array}
     */
    parseData(list, id, field, Ids) {
      if (Array.isArray(list)) {
        if (list.find(value => value.id === id)) {
          let listArr = list.find(value => value.id === id)[field] || []
          if (Ids) {
            listArr = listArr.filter(item => Ids.some(ids => ids === item.id) || item.useFlag === '1')
          } else if (listArr[0].hasOwnProperty('useFlag')) {
            listArr = listArr.filter(item => item.useFlag === '1')
          }
          return listArr
        } else {
          return []
        }
      }
    },
    /**
     * 开始时间输入限定（周转表/工序表）
     * @param currentEnd 工序计划完成时间（周转/工序）
     */
    getPickerOptionsStart(currentEnd) {
      let date = currentEnd || new Date()
      const minMillisecond = this.todayMillisecond
      const maxMillisecond = this.moment(date).unix() * 1000
      return {
        // 工序计划开始时间不能小于当前时间且不能大于计划完成时间
        disabledDate(time) {
          if (currentEnd) {
            return time.getTime() < minMillisecond || time.getTime() > maxMillisecond
          } else {
            return time.getTime() < minMillisecond
          }
        }
      }
    },
    /**
     * 完成时间输入限定（周转表/工序表）
     * @param currentStart 工序计划开始时间（周转/工序）
     */
    getPickerOptionsEnd(currentStart) {
      let start = this.todayMillisecond
      // 对比是否有计划开始时间以及计划开始时间是否在当前时间之后
      if (currentStart && this.moment(currentStart).isAfter(this.todayMillisecond)) {
        start = this.moment(currentStart).unix() * 1000
      }
      const minMillisecond = this.moment(start).subtract(1, 'days').unix() * 1000 + 1
      return {
        // 工序计划完成时间不能小于工序计划开始时间和当前时间
        disabledDate(time) {
          return time.getTime() < minMillisecond
        }
      }
    },
    // 判断是否是已完成的工序进度返回表格样式
    isFinished({row}) {
      let id = row.workstageProcessStatusId
      let list = this.workstageProcessStatus
      let item = list.find((item) => item.id === id)
      if (item) {
        return (item.value === 'Finished' || item.value === 'Started') ? 'row_isFinished' : ''
      }
    },
    // 判断是否是已完成的工序进度返回选择禁用
    isDisabled(row) {
      let id = row.workstageProcessStatusId
      let list = this.workstageProcessStatus
      let item = list.find((item) => item.id === id)
      if (item) {
        return item.value === 'Finished' || item.value === 'Started'
      }
    },
    // 班组选择切换
    workgroupChange(row) {
      if (row.workgroupId) {
        row.workcenterId = ''
        row.workCenterList = this.parseData(row.nametree, row.workgroupId, 'workcenter', [row.workcenterId])
        row.deviceList = []
        row.staffList = []
        row.deviceIds = []
        row.staffIds = []
      }
    },
    // 工作中心切换
    workcenterChange(row) {
      if (row.workcenterId) {
        row.deviceIds = []
        row.staffIds = []
        row.workCenterList = this.parseData(row.nametree, row.workgroupId, 'workcenter', [row.workcenterId])
        row.deviceList = this.parseData(row.workCenterList, row.workcenterId, 'device', row.deviceIds)
        row.staffList = this.parseData(row.workCenterList, row.workcenterId, 'staff', row.staffIds)
      }
    },
    removeTagSelect(row, type) {
      if (type === 'device') {
        row.deviceList = row.deviceList.filter(item => row.deviceIds.some(id => id === item.id) || item.useFlag === '1')
      } else if (type === 'staff') {
        row.staffList = row.staffList.filter(item => row.staffIds.some(id => id === item.id) || item.useFlag === '1')
      }
    },
  }
}
</script>

<style lang="less">
  .disabled_select{
    .el-select-dropdown__item.is-disabled{
      color: #c0c4cc!important;
      font-weight: normal!important;
    }
  }
  .workstage_tab {
    .el-table__body td {
      &.table_select{
        .cell{
          padding: 0 !important;
          .el-input__inner{
            padding: 0 10px!important;
          }
        }
      }
      .el-date-editor--date input{
        padding: 0 20px!important;
      }
      .el-input__prefix{
        left: -6px;
      }
      .type_list{
        width: 100%;
        &.error_input{
          .el-input__inner{
            color: @mesTableInputEFC;
          }
        }
      }
    }
    .el-table tr.row_isFinished{
      td{
        background-color: #f5f7fa;
      }
    }
  }
</style>
